<template>
    <el-autocomplete v-model="model" :fetch-suggestions="remoteMethod" placeholder="请输入关键词" @select="handleSelect" style="width:100%"></el-autocomplete>
</template>

<script>
import { listSubject } from 'api/common';

export default {
    props: {
        value: {
            type: [String, Number],
            required: true
        }
    },
    computed: {
        model: {
            get() {
                return this.value
            },
            set(val) {
                this.$emit('input', val);
            }
        }
    },
    data() {
        return {
            list: null,
            subjectName:''
        }
    },
    methods: {
        remoteMethod(query, cb) {
            if(query==''){
               cb('')
            };
            if(this.subjectName!=query && this.subjectName!=''){
                this.$emit('change','');
            }
            if (query) {
                listSubject(query).then(response => {
                   this.list = response.data.content;
                   if(this.list==''){
                       return;
                   }
                }).then(() => {
                    let results = this.list.filter(this.createStateFilter(query));
                    clearTimeout(this.timeout);
                    this.timeout = setTimeout(() => {
                        cb(results);
                    }, 200 * Math.random());
                });
            }  
        },
        createStateFilter(query) {
            return (state) => {
                state.value = state.subjectName; 
                return (state.value.toLowerCase().includes(query.toLowerCase()));
            };
        },
        handleSelect(val) {
            this.subjectName = val.subjectName;
            this.$emit('change', val.subjectId);
        },
    }
}
</script>

<style>

</style>
